package com.huang.weic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huang.weic.bean.Vo.ViewVo;
import com.huang.weic.bean.comm;
import com.huang.weic.bean.frend;
import com.huang.weic.bean.view;;
import com.huang.weic.mapper.CommMapper;
import com.huang.weic.mapper.ViewMapper;
import com.huang.weic.mapper.frendMapper;
import com.huang.weic.service.viewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ViewServiceImpl extends ServiceImpl<ViewMapper, view> implements viewService {
   @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ViewMapper viewMapper;
    @Autowired
    private CommMapper commMapper;
    @Autowired
    private frendMapper frendMapper;

    @Override
    public List<Object>  selectViewList(String openid) {
        List<ViewVo> list = viewMapper.getList();
        //根据openid 获取朋友发表的动态
        //先获取朋友 id
        QueryWrapper<frend> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("openid",openid).select("frend_openid");
        List<frend> frends = frendMapper.selectList(wrapper1);
        //遍历每个朋友
        for (frend frend : frends) {
            List<ViewVo>  setList=frendMapper.getViewByopenid(frend.getFrendOpenid());
            //将一个朋友的所有朋友圈 放入list里
            for (ViewVo viewVo : setList) {
                list.add(viewVo);
            }
        };
        //排序 去重
        List<ViewVo> collect = list.stream().distinct().sorted(Comparator.comparing(ViewVo::getGtmCreate).reversed()).collect(Collectors.toList());


        List<Object> all = new ArrayList<>();
        for (ViewVo vo : collect) {
            //查找该动态下的评论
            QueryWrapper<comm> wrapper = new QueryWrapper<>();
            wrapper.eq("view_id",vo.getId());
            List<comm> commList = commMapper.selectList(wrapper);
            //返回的集合
            Map<String, Object> map = new HashMap<>();
            if(vo.getImgList()!=null){
                String[] urlList = vo.getImgList().split(";");
                map.put("urlList",urlList);
            }
            if(vo.getVideoUrl()!=null){
                String videoUrl = vo.getVideoUrl();
                map.put("videoUrl",videoUrl);
            }

            Integer id = vo.getId();
            String viewId = String.valueOf(id);
            Set<Object> love = redisTemplate.opsForSet().members(viewId);

            map.put("love",love); map.put("viewVo",vo);

            map.put("commList",commList);
            all.add(map);
        }



        return all;
    }

}
